<?php


namespace app\common\library\xilujob;

use think\Env;
use think\Exception;
use think\Log;
use function fast\array_get;

class TencentMap {

    protected $baseUri = 'https://apis.map.qq.com';

    protected $key;
    protected $sk;

    public function __construct($key, $sk) {
        $this->key = $key;
        $this->sk = $sk;
    }

    public static function default() {
        $key = Env::get('tencent_map.key');
        $sk = Env::get('tencent_map.sk');
        if(!$key || !$sk) {
            throw new Exception(__('tencent map key,sk not config'));
        }
        return new static($key,$sk);
    }

    /**
     * 发送带签名的get请求
     * @param $uri
     * @param $params
     * @return array
     */
    protected function get($uri, $params) {
        $params['key'] = $this->key;
        ksort($params);
        $queryStr = $queryStrEncoded = '';
        foreach($params as $key=>$value) {
            $queryStr .= '&'."$key=$value";
            $queryStrEncoded .= '&'."$key=".urlencode($value);
        }
        $queryStr = ltrim($queryStr, '&');
        $queryStrEncoded = ltrim($queryStrEncoded, '&');
        $sigData = $uri . '?' . $queryStr . $this->sk;
        $sig = md5($sigData);
        $url = $this->baseUri. $uri . '?' . $queryStrEncoded . '&sig=' . $sig;
        try {
            $res = file_get_contents($url);
            $res = json_decode($res, true);
            $status = array_get($res, 'status', null);
            if ($status === null) {
                return [];
            }
            return $res;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            return [];
        }
    }

    /**
     * 将地址解析为经纬度
     * @param string $address
     * @see https://lbs.qq.com/webservice_v1/guide-geocoder.html
     * @return array
     */
    public function convertAddressToGeo($address) {
        if(!($address=trim($address))) {
            throw new LogicException('地址不能为空');
        }
        $res = $this->get('/ws/geocoder/v1', ['address'=>$address]);
        return $res;
    }

}